using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


using System.Collections.Generic;
using DotNetNuke;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security.Roles;
using DotNetNuke.Entities.Modules.Communications;

namespace Jfc007.WebLib
{
   
    public partial class Docs : PortalModuleBase, IActionable, IModuleListener
    {
       

       

        public void OnModuleCommunication ( object s, ModuleCommunicationEventArgs e )
        {
            DocumentsController controller = new DocumentsController();
          //  int modId = controller.GetWebLibModuleId( PortalId );
            switch (e.Sender)
            {

                case "Actions":
                    if (e.Text == "Delete")
                    {


                        // Copy the items in the Rows collection into an array.
                        GridViewRow[] rowArray = new GridViewRow[grdDocuments.Rows.Count];
                        grdDocuments.Rows.CopyTo( rowArray, 0 );

                        foreach (GridViewRow row in rowArray)
                        {
                            Control ctl = row.Controls[1];// get the second control reference
                            Boolean selected = ((System.Web.UI.WebControls.CheckBox)(ctl.Controls[1])).Checked;
                            if (selected)
                            {
                                Control ctlLink = row.Controls[0];// get the first control reference
                                string selectedGuid = ((System.Web.UI.WebControls.HyperLink)(ctlLink.Controls[1])).NavigateUrl;
                                int endPos = selectedGuid.LastIndexOf( '/' );
                                string strGuid = selectedGuid.Substring( endPos - 36, 36 );

                                controller.DeleteDocument( PortalId, new Guid( strGuid ) );
                            }
                        }
                    }
                    else if (e.Text == "Refresh")
                    {
                        grdDocuments.DataSource = controller.GetDocuments( PortalId, this.UserId );
                        grdDocuments.DataBind();
                        break;
                    }
                    else if (e.Text == "Stars")
                    {
                        // Copy the items in the Rows collection into an array.
                        GridViewRow[] rowArray = new GridViewRow[grdDocuments.Rows.Count];
                        grdDocuments.Rows.CopyTo( rowArray, 0 );

                        foreach (GridViewRow row in rowArray)
                        {
                            Control ctl = row.Controls[1];// get the second control reference
                            Boolean selected = ((System.Web.UI.WebControls.CheckBox)(ctl.Controls[1])).Checked;
                            if (selected)
                            {
                                Control ctlLink = row.Controls[0];// get the first control reference
                                string selectedGuid = ((System.Web.UI.WebControls.HyperLink)(ctlLink.Controls[1])).NavigateUrl;
                                int endPos = selectedGuid.LastIndexOf( '/' );
                                string strGuid = selectedGuid.Substring( endPos - 36, 36 );


                                int stars = Convert.ToInt32(((System.Web.UI.WebControls.Image)(row.Controls[2].Controls[1])).ImageUrl.Substring( 13, 1 ));
                                if (Convert.ToInt32( stars ) < 5)
                                    stars = 1;
                                else
                                    stars = -5;
                                
                                controller.UpdateStars( stars, PortalId, new Guid( strGuid ) );
                            }
                        }

                        grdDocuments.DataSource = controller.GetDocuments( PortalId, this.UserId );
                        grdDocuments.DataBind();
                        break;
                    }
                    break;
                case "Categories":
                    grdDocuments.DataSource = controller.GetDocumentsByCategory( PortalId, this.UserId, e.Text );
                    grdDocuments.DataBind();
                    break;
                case "Stars":
                    grdDocuments.DataSource = controller.GetDocumentsByStars( PortalId, this.UserId, Convert.ToInt32(e.Text) );
                    grdDocuments.DataBind();
                    break;

            }

        }

        private long GetQuota
        {
            get
            {
               

                
                string[] roles = UserInfo.Roles;
                long quota = 0;
                if (roles != null)
                {
                    //RoleManagerModule aa =new RoleManagerModule();
                    RoleController rolesController = new RoleController();
                    for (int i = 0; i < roles.Length; i = i + 1)
                    {
                        long roleQuota = 0;

                        //talvez devesse verificar o nome
                        string roleName = roles[i];
                        RoleInfo roleInfo = rolesController.GetRoleByName(PortalId, roleName);
                        Int64.TryParse(roleInfo.Description, out roleQuota);
                        if (quota < roleQuota)
                            quota = roleQuota;
                    }
                }

                return quota;
            }
        }


        protected void Page_Load ( object sender, EventArgs e )
        {
            if ((!Page.IsPostBack))
            {
            //    this.OnModuleCommunication += new DotNetNuke.Entities.Modules.Communications.ModuleCommunicationEventHandler( OnModuleCommunication );
                //this.ModuleCommunicationEventArgs += new ModuleCommunicationEventHandler( this.OnModuleCommunication );
            }
                
          
              //  this.ModuleCommunication += new ModuleCommunicationEventHandler( OnModuleCommunication );
           
            /**/

           
                AddDownloadLink( Localization.GetString( "Description.Header", LocalResourceFile ), "ctlDownloadLink" );
                AddDocumentColumn( Localization.GetString( "Category.Header", LocalResourceFile ), "Category" );
                AddDocumentColumn( Localization.GetString( "Keywords.Header", LocalResourceFile ), "Keywords" );
                AddDocumentColumn( Localization.GetString( "Size.Header", LocalResourceFile ), "SizeLenText" );
                AddDocumentColumn( Localization.GetString( "ModifiedDate.Header", LocalResourceFile ), "CreatedDate", "{0:d}" );

                //Localize the Data Grid
                //Localization.LocalizeDataGrid(grdDocuments, Me.LocalResourceFile)

                // Only read from the cache if the users is not logged in

                string strCacheKey = this.CacheKey + ";anon-doclist";
                List<DocumentInfo> m_documentList = null;
                if (!(Request.IsAuthenticated))
                {
                    m_documentList = (List<DocumentInfo>)DataCache.GetCache( strCacheKey );
                }

                DocumentsController controller = new DocumentsController();
                long totalSize = 0;

                if (m_documentList == null)
                {
                    int modId = controller.GetWebLibModuleId( PortalId );
                    m_documentList = controller.GetDocuments( PortalId, this.UserId );
                    totalSize = controller.GetTotalSize( PortalId, this.UserId );
                }

                if (!(UserInfo.IsSuperUser))
                {
                    long quota = GetQuota;

                    lblSize.Text = String.Format( Localization.GetString( "UsedSpace.Text", LocalResourceFile ),
                        DocumentInfo.ByteSizeToString( totalSize ),
                        DocumentInfo.ByteSizeToString( quota ) );
                }
                else
                {
                    lblSize.Visible = false;
                }

                //   Only write to the cache if the user is not logged in
                if (Request.IsAuthenticated)
                    DataCache.SetCache( strCacheKey, m_documentList, new TimeSpan( 0, 5, 0 ) );

                grdDocuments.DataSource = m_documentList;
                grdDocuments.DataBind();

          
        }

        public string EditFile(Guid fileId)
        {
            string strFileId = Convert.ToString(fileId);
            return DotNetNuke.Common.Globals.NavigateURL(TabId, "EditDocuments", "mid=" + Convert.ToString(ModuleId), "FileId=" + strFileId);
          //  return DotNetNuke.Common.Globals.NavigateURL( TabId, "EditDocuments",  "FileId=" + strFileId );

        }

        #region Optional Interfaces


        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Registers the module actions required for interfacing with the portal framework
        /// </summary>
        /// <value></value>
        /// <returns></returns>
        /// <remarks></remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        public ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();

                long quota = GetQuota;
                DocumentsController controller = new DocumentsController();
                long totalSize = controller.GetTotalSize(PortalId, this.UserId);
                Boolean isShowEdit = false;

                if ((totalSize <= quota) || (UserInfo.IsSuperUser))
                {
                    isShowEdit = true;
                    string url = DotNetNuke.Common.Globals.NavigateURL(TabId, "EditDocuments", "mid=" + Convert.ToString(ModuleId), "");
                    
                    Actions.Add(this.GetNextActionID(), Localization.GetString("AddContent.Action", LocalResourceFile), ModuleActionType.AddContent, "", "", url, false, SecurityAccessLevel.View, isShowEdit, false);

                }
                return Actions;
            }
        }
        public bool IsShowEdit()
        {
            //return DotNetNuke.Security.Permissions.ModulePermissionController.HasModulePermission( ModuleConfiguration.ModulePermissions, "EDIT" );
            return true;
        }

        #endregion
        #region Private Methods
        /// <summary>
        ///  Dynamically adds a column to the datagrid
        /// </summary>
        /// <param name="DataField">The name of the property to read data from</param>
        private void AddDocumentColumn(string DataField)
        {
            AddDocumentColumn(DataField, DataField, "");
        }

        /// <summary>
        ///  Dynamically adds a column to the datagrid
        /// </summary>
        ///  <param name="Title">The name of the property to read data from</param>
        /// <param name="DataField">The name of the property to read data from</param>
        private void AddDocumentColumn(string Title, string DataField)
        {
            AddDocumentColumn(Title, DataField, "");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Title">The name of the property to read data from</param>
        /// <param name="DataField">The name of the property to read data from</param>
        /// <param name="Format">Format string for value</param>
        private void AddDocumentColumn(string Title, string DataField, string Format)
        {
            //AddDocumentColumn(Title, DataField, Format, "")
            BoundField objBoundColumn;


            objBoundColumn = new BoundField();

            objBoundColumn.DataField = DataField;
            objBoundColumn.DataFormatString = Format;
            objBoundColumn.HeaderText = Title;
            objBoundColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
            objBoundColumn.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;

            objBoundColumn.HeaderStyle.CssClass = Title + "Header"; //"NormalBold"
            objBoundColumn.ItemStyle.CssClass = Title + "Cell";  //"Normal"

            this.grdDocuments.Columns.Add(objBoundColumn);

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Title">The name of the property to read data from</param>
        /// <param name="DataField">The name of the property to read data from</param>
        /// <param name="Format">Format string for value</param>

        private void AddCheckBox ( string Title, string Name )
        {
            TemplateField objTemplateColumn;
            string strCellPrefix;

            objTemplateColumn = new TemplateField();
            objTemplateColumn.ItemTemplate = new CheckboxColumnTemplate ( Name, "checkbox", ListItemType.Item );
            objTemplateColumn.HeaderText = Title;

            strCellPrefix = Title;

            objTemplateColumn.HeaderStyle.CssClass = strCellPrefix + "Header"; //'"NormalBold"
            objTemplateColumn.ItemStyle.CssClass = strCellPrefix + "Cell"; //"Normal"

            this.grdDocuments.Columns.Add( objTemplateColumn );
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="Title">The name of the property to read data from</param>
        /// <param name="DataField">The name of the property to read data from</param>
        /// <param name="Format">Format string for value</param>

        private void AddDownloadLink(string Title, string Name)
        {
            TemplateField objTemplateColumn;
            string strCellPrefix;

            objTemplateColumn = new TemplateField();
            objTemplateColumn.ItemTemplate = new DownloadColumnTemplate(Name, "Download", ListItemType.Item);
            objTemplateColumn.HeaderText = Title;
            objTemplateColumn.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
            objTemplateColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Right;

            strCellPrefix = Title;
            if ((String.IsNullOrEmpty(strCellPrefix)) && (Name == "ctlDownloadLink"))
            {
                strCellPrefix = "Download";
            }

            objTemplateColumn.HeaderStyle.CssClass = strCellPrefix + "Header"; //'"NormalBold"
            objTemplateColumn.ItemStyle.CssClass = strCellPrefix + "Cell"; //"Normal"

            this.grdDocuments.Columns.Add(objTemplateColumn);
        }

#endregion

        protected void GrdDocuments_RowCreated(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                GridViewRow row = e.Row;
                DocumentInfo doc = (DocumentInfo)row.DataItem;

                if (row.FindControl("ctlDownloadLink") != null)
                {
                    
                    Guid fileId = doc.FileGuid;
                    HyperLink link = (HyperLink)row.FindControl("ctlDownloadLink");
                    link.Text = doc.FileDescription;
                    string searchTabID = Convert.ToString(Settings["TabDisplayBinaryData"]);
                    if (!String.IsNullOrEmpty(searchTabID))
                    {

                        link.NavigateUrl = DotNetNuke.Common.Globals.NavigateURL(Convert.ToInt32(searchTabID), string.Empty, "FileId=" + Convert.ToString(fileId));

                        link.Target = "_blank";
                    }
                }

                if (row.FindControl( "imgStar" ) != null)
                {
                    
                    Guid fileId = doc.FileGuid;
                    Image img = (Image)row.FindControl( "imgStar" );
                    img.ImageUrl =@".\Images\star"+Convert.ToString(doc.Stars)+ ".gif";
                    //Usar a variavel doc para saber as estrelas
                }

            }
        }
    }

}